<template>
  <view class="cart">
    <!-- 头部 -->
    <!--<view class="header">
      <span></span>
      <span @click='editor'>
        <span v-if="editorFlag">编辑</span>
        <span v-else>完成</span>
      </span>
    </view>-->
    <!-- 头部结束 -->
	<view class="goods-section" v-if="valueData.length>0">
		<!-- 购物车内容 -->
		 <view class="cart_list" v-for="(shopItem,shopIndex) in valueData" :key="shopIndex"  v-if="shopItem.cart_item.length>0">
			 <view class="shop-header">
				<image class="shop-icon" src="../../static/cart/jiaonang.png"></image>
				<text>{{shopItem.name}}</text>
				<!-- <image class="back" src="../../static/cart/fanhui.png"></image> -->
			 </view>
		      <checkbox-group>
		        <view class="slide" @touchstart="touchS" @touchmove="touchM($event,index)"  v-for="(item,index) of shopItem.cart_item" :key="index">
					<view class="contents_wrapper"  :data-type="item.type">
					    <view class="cart_list_item">
					        <view class="checked_wrapper" @click.stop="seletItem(shopIndex,index,item.id)">
					            <checkbox  :value="index" :checked="item.checked"/>
					            <view class="checked_layer"></view>
					        </view>
					        <img :src="item.medicine_info.thumb_url" class="cart_list_item_pic" mode="aspectFill" @click.stop="toGoodsDetail(item.merchant_id)">
					        <view class="cart_list_item_right" @click.stop="toGoodsDetail(item.merchant_medicine_id)">
					            <view class="cart_list_item_name">{{item.medicine_info.name}}</view>
					            <!-- <view class="cart_list_item_desc" v-show='item.goods_info.goods_spu_info'>规格: {{item.goods_info.goods_spu_info.spu_name}}</view> -->
					            <view class='count'>
					                    <view style="color: #F06322;">￥{{item.medicine_info.selling_price}}</view>
					                <view class="count_btn">
					                    <view  :class="{decrease:true,decrease_least:item.num==flag}" @click.stop="">-</view>
					                    <view class="input_num">
					                      <view class="input_num_layer"></view>
					                      <input type="number" :value='item.num' readonly>
					                      </view>
					                    <view class="increase decrease_least" @click.stop="">+</view>
					                </view>
					            </view>
					        </view>
					    </view>
					</view>
					<view class="delete" @click="delt([item.id])">删除</view>
		        </view>
		    </checkbox-group>
		</view>
		<!-- 购物车内容结束 -->
	</view>

	<!-- <view class="tip">
		<view class="tip-left">
			<view class="pei-song">商家配送</view>
			<view>再买<span style="color: #F47021;">￥26.20</span>起送(不含配送费)</view>
		</view>
		<view class="tip-right">
			去凑单
		</view>
	</view> -->

    <!-- 结算栏 -->
    <footer>
      <view class="footer_left">
        <checkbox @click="selectAll" :checked="checkedAll"/>
        <label>全选</label>
      </view>
      <view class="footer_right">
        <view class="footer_right_price" v-if="editorFlag&&selectIdArr.length>0"><span style="color: #FFFFFF;font-size: 12px;">合计：</span>￥{{money}}</view>
        <view v-if="editorFlag" :class="{footer_right_pay:true,hasItem:isSelectedOne}" @click="helperShopCartChange">
          <span>去结算</span>
        </view>
		<view  v-else class="footer_right_pay" :class="{hasItem:isSelectedOne}" @click="delt(selectIdArr)">
		  <span>删除</span>
		</view>
      </view>
    </footer>
    <!-- 结算栏结束 -->
  </view>
</template>

<script>

export default {
  data() {
    return {
		editorFlag: true,//编辑为true，完成为false
		valueData: [],
		selectIdArr: [],//选中状态的id数组
		slideIndex: [],
		checkedAll: false,
		money: '',//总金额
		clientX1: '',//滑动开始位置
		clientX2: '',
		// del:0,//内容初始的right距离
		btnWidth: 80,//删除按钮宽度
		flag: 1,
		page: 1,
		isSelectedOne: false,
		total: 0,//购物车全部数量
		key: '',
		agent_phone_number: '',
		agent_email: '',
		btnLoading: false //防止重复点击确认按钮
    }
  },
  watch:{
      valueData:{
          handler:function(nval){
              this.money=0
              for(let p of nval){
				  p.cart_item.forEach((item,index) => {
					if(item.checked==1){
					  this.money+=parseFloat(item.medicine_info.selling_price) * parseInt(item.num)
					}
				  })
              }
              this.money = this.money.toFixed(2);
			  //判断是否有选中的 直接在渲染层判断selectIdArr无效 TODO
			  console.log(this.selectIdArr)
			  if(this.selectIdArr.length>0){
				  this.isSelectedOne = true;
			  } else{
				  this.isSelectedOne = false;
			  }
			  if(this.total==this.selectIdArr.length&&this.selectIdArr.length!=0){
				  this.checkedAll = true;
			  } else{
				  this.checkedAll = false;
			  }
          },
          deep:true
      }
  },

	onLoad(options){
  		this.key = options.key
	},

  methods: {


  	async helperShopCartChange() {
  		//未选择商品不能调用
  		if(this.selectIdArr.length==0){
  			return
		}
  		if(this.btnLoading){
  			return
		}
  		this.btnLoading = true
  		let res = await this.$api.helperShopCartChange({
			shop_cart_ids: this.selectIdArr,
			wx_openid: wx.getStorageSync("wx_openid")
		},this.$baseUrl)
		if(res.data.level==="success"){
			let data = res.data
			this.agent_email = data.pharmacist_info.agent_email
			this.agent_phone_number = data.pharmacist_info.agent_phone_number
			this.toOrder(data.data)
		} else {
			this.btnLoading = false
			this.$currency.showToast(res.data.message)
		}
	},

    toGoodsDetail(id){
      wx.navigateTo({url:'/pages/goodsDetail/goodsDetail?id='+id})
    },
    async decrease(item){  //计数器的减
		if(parseInt(item.num)<=1){
			return
		}
		wx.showLoading({
			title: '加载中'
		})
        let userToken=wx.getStorageSync('userToken')
        const id=item.merchant_medicine_id;
        /* const good_spu_id=item.goods_spu_id */
        let res=await this.$api.addShopCart({
          medicine_id:id,
          change:-1,
          user_token:userToken,
          /* goods_spu_id:good_spu_id */
        },this.$baseUrl)
        if(res.data.level=='success'){
        	this.getCartList()
        } else{
        	wx.hideLoading()
        	wx.showToast({
        		title: res.data.message,
        		icon: 'none'
        	})
        }
        wx.hideLoading()
    },
    async increase(item){//计数器的加
		wx.showLoading({
			title: '加载中'
		})
		let userToken=wx.getStorageSync('userToken')
		const id=item.merchant_medicine_id;
		/* const good_spu_id=item.goods_spu_id */
		let res=await this.$api.addShopCart({
		  medicine_id:id,
		  change: +1,
		  /* goods_spu_id:good_spu_id, */
		  user_token:userToken,
		},this.$baseUrl);
		if(res.data.level=='success'){
		  this.getCartList()
		} else{
			wx.hideLoading()
			wx.showToast({
				title: res.data.message,
				icon: 'none'
			})
		}
		wx.hideLoading()
    },
    touchS(e){
        // console.log(e)
        this.clientX1=e.clientX
    },
    touchM(e,index){
        this.clientX2=e.clientX
        let disX=this.clientX1-this.clientX2
        if (disX == 0 || disX < 0) {//如果移动距离小于等于0，说明向右滑动，文本层位置不变
            // this.del = 0;
            this.$set(this.valueData[index],'type',0)
        }
        if (disX >= this.btnWidth) {
            //控制手指移动距离最大值为删除按钮的宽度
            // this.del =this.btnWidth;
            this.$set(this.valueData[index],'type',1)
        }

    },
    async delt(id){//删除选中的购物车商品
		wx.showLoading({
			title: '删除中'
		})
        let userToken=wx.getStorageSync('userToken')
        let res=await this.$api.deleteShopCart({shop_cart_ids:id,user_token:userToken},this.$baseUrl)
        if(res.data.level=="success"){
			this.selectIdArr.length=0;
            this.getCartList()
        } else{
			wx.showToast({
				title: res.data.message,
				icon: 'none'
			})
		}
		wx.hideLoading()
    },
    checkboxChange(e) {//获取checkobx选中的value数组
        // console.log('checkbox发生change事件，携带value值为：', e.mp.detail)
        this.slideIndex=e.mp.detail.value;

    },
    seletItem(shopIndex,index,id){//选中商品
		if(this.valueData[shopIndex].cart_item[index].checked==0){
		    this.$set(this.valueData[shopIndex].cart_item[index],'checked',1)
		    if(!this.selectIdArr.includes(id)){
		        this.selectIdArr.push(id)
		    }
		}else{
		    this.$set(this.valueData[shopIndex].cart_item[index],'checked',0);
		    let arr=this.selectIdArr
		    let arr2=[]
		    arr.forEach((val)=>{
		        if(val!=id){
		            arr2.push(val)
		        }
		    })
		    this.selectIdArr=arr2
		}
		console.log(this.selectIdArr)
    },
    editor(){//显示编辑，完成
      let flag=this.editorFlag;
      this.editorFlag=!flag;
    },
	  async getCartList(type = '') {
		  if (type != 'more') {//type为more，是上拉加载更多
			  this.page = 1
		  }
		  let userToken = wx.getStorageSync('userToken')
		  let merchant = wx.getStorageSync('merchant')
		  let params = {
			  user_token: userToken,
			  page: this.page,
			  limit: 10,
			  merchant_id: merchant.merchant_id,
			  wx_openid: wx.getStorageSync("wx_openid"),
			  key: this.key
		  }
		  let res = await this.$api.getFictitiousShopCart(params, this.$baseUrl)

		  //判断购物车数据中的商品是否有值，把有值的帅选出来
		  if (res.data.level == "success") {
			  if (res.data.data && res.data.data.length > 0) {
				  res.data.data.forEach((item, index) => {
					  let tempData = []
					  item.cart_item.forEach((item2, index2) => {
						  if (item2.medicine_info.id) {
							  tempData.push(item2)
						  }
					  })
					  item.cart_item = tempData
				  })
			  }
		  }

		  if (res.data.level == 'success' && this.selectIdArr.length == 0) {
			  res.data.data.forEach((shopItem, index) => {
				  shopItem.cart_item.map((item) => {
					  item.type = 0//1为右划状态
					  item.checked = 0;//1为选项选中状态
				  })
			  })
			  wx.hideLoading()
		  } else if (res.data.level == 'success' && this.selectIdArr.length != 0) {
			  res.data.data.forEach((shopItem, index) => {
				  shopItem.cart_item.map((item) => {
					  item.type = 0//1为右划状态
					  if (this.selectIdArr.includes(item.id)) {
						  item.checked = 1;//1为选项选中状态
					  } else {
						  item.checked = 0;//1为选项选中状态
					  }
				  })
			  })
			  wx.hideLoading()
		  }
		  if (type == 'more') {
			  if (res.data.data.length == 0) {
				  this.page--;
			  } else {
				  res.data.data.forEach((val) => {
					  this.valueData.push(val)
				  })
			  }
		  } else {
			  this.valueData = res.data.data
		  }

		  //获取当前购物车的全部数量 TODO 需要遍历店铺，再遍历商铺里的商品，但好像只有一个店铺 可优化
		  this.total = 0;
		  for (let shop of this.valueData) {
			  shop.cart_item.forEach((item, index) => {
				  this.total++;
			  })
		  }
	  },
    async selectAll(){//全选
        let flag=this.checkedAll;
        let arr=this.valueData;
        this.selectIdArr
        if(flag==false){
			this.valueData.forEach((shopItem,index) => {
				shopItem.cart_item.map((item)=>{
				    item.type=0//1为右划状态
				    item.checked=1;//1为选项选中状态
				    this.selectIdArr.push(item.id)
				})
			})
        }else{
			this.valueData.forEach((shopItem,index) => {
				shopItem.cart_item.map((item)=>{
				    item.type=0//1为右划状态
				    item.checked=0;//1为选项选中状态
				    this.selectIdArr=[]
				})
			})
        }
        this.checkedAll=!flag
      },
    async toOrder(selectIdArr){
		if(selectIdArr.length==0){
          return
        }
        wx.showLoading({
			title: '加载中'
		})
        let userToken=wx.getStorageSync('userToken')
        let res=await this.$api.submitOrder({
          shop_cart_ids:selectIdArr,
          num:'',
		  user_token: userToken
        },this.$baseUrl)
        if(res.data.level=="success"){
            wx.hideLoading()
			res.data.data.shop_cart = selectIdArr
            this.$store.dispatch('setOrder',res.data.data)
            wx.navigateTo({url:'/pages/orderConfirm/orderConfirm?type=cart&agent_email='+this.agent_email + '&agent_phone_number='+this.agent_phone_number})
      } else {
		  wx.hideLoading()
		  wx.showToast({
		  	title: res.data.message,
		  	icon: 'none'
		  })
	  }
    }
  },
  onShow(){
	   wx.showLoading({
		   title: '加载中'
	   })
      this.getCartList()
      this.selectIdArr=[]
      /* this.$store.dispatch('setCoupon','') *///用来清空优惠券，只能这里清空
      this.checkedAll=false//复位全选按钮
	  this.btnLoading = false //把提交按钮设置为可用
    },
 onReachBottom(){
    this.page++;
    this.getCartList('more')
  },


}
</script>

<style>
/* 小程序checkbox的自定义样式，且不能用scoped */
.footer_left checkbox .wx-checkbox-input{
    border-radius: 50%;
    height: 20px;
    width: 20px;
    margin-top: -4px;
    border: 1px solid #eee;
	background-color: #222222;
}
 checkbox .wx-checkbox-input{
    border-radius: 50%;
    height: 20px;
    width: 20px;
    margin-top: -4px;
    border: 1px solid #eee;
}
checkbox .wx-checkbox-input.wx-checkbox-input-checked::before {
  height: 20px;
  width: 20px;
  line-height: 20px;
  text-align: center;
  font-size: 20px;
  padding: 5px;
  color: #fff;
  border-radius: 50%;
  background-color: red;
  border:1px solid #eee
}
</style>
<style scoped>
.cart{
  width:100%;
  min-height: 100vh;
  overflow-x:hidden;
  /*background:#000000;*/
  background: #F2F2F2;
}
  .header{
	position: fixed;
	top: 0;
	left: 0;
    width:100%;
    height: 40px;
    background: #ffffff;
    display:flex;
    justify-content: space-between;
    align-items:center;
    /*border-bottom: 1px solid #555555;*/
    /* border-bottom: 1px solid #eeeeee; */
  }
  .header>span:nth-child(1){
	  font-size: 16px;
	  color: #212121;
	  font-weight: bold;
		position: absolute;
		left: 50%;
		transform: translate(-50%,0);
  }
  .header>span:nth-child(2){
	  position: absolute;
	  right: 10px;
	  color: #989999;
  }

  /* 商品列 */
  .goods-section{
	  height: calc(100vh - 60px);
	  padding: 0 12px;
	  overflow: auto;
	}
  .cart_list{
    width:100%;
	margin-top: 10px;
	overflow: hidden;
	border-radius: 10px;
  }

  .shop-header{
	width:100%;
	height: 40px;
	background: #ffffff;
	display:flex;
	align-items:center;
	font-size: 14px;
	border-bottom: 1px solid #eeeeee;
  }
  .shop-header .shop-icon{
		width: 14px;
		height: 14px;
		margin-left: 10px;
	}
	.shop-header .back{
		width: 5px;
		height: 10px;
	}
	.shop-header text{
		color: #6C6D6C;
		margin: 0 10px;
	}

  .checked_wrapper{
      position: relative;
      width:50px;
      height: 100%;
  }
  .checked_wrapper>checkbox{
      position:absolute;
      top:calc(50% - 11px);
      left:calc(50% - 11px);
      transform:translate(-calc(50% - 11px));
      width: 22px;
      height: 22px;
  }
    .checked_wrapper>.checked_layer{
        position:absolute;
        z-index:999;
        width:100%;
        height:100%;
    }


	.tip{
		background:#F8F1CB;
		position:fixed;
		z-index:101;
		bottom:65px;
		height:40px;
		width: calc(100% - 24px);
		left: 12px;
		display:flex;
		align-items:center;
		justify-content:space-between;
	}
	.tip-left{
		display: flex;
		align-items: center;
	}
	.tip-left .pei-song{
		padding: 3px 5px;
		border: 1px solid #F09253;
		font-size: 10px;
		color: #F09253;
		margin: 0 10px;
	}
	.tip-left view{
		color: #676867;
		font-size: 12px;
	}
	.tip-right{
		font-size: 12px;
		color: #F47021;
		margin-right: 10px;
		font-weight: bold;
	}

  /* 结算栏 */
  footer{
    background:#222222;
    position:fixed;
    z-index:101;
    bottom:10px;
    height:45px;
    width: calc(100% - 24px);
	border-radius: 20px;
	overflow: hidden;
	left: 12px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    color: #ffffff;
  }
  .footer_left{
    /*margin-left:10px;*/
  }
  .footer_left>checkbox{
    margin: 0 14px;
    width: 22px;
    height: 22px;
  }
  .footer_right{
    display:flex;
    align-items:center
  }
  .footer_right_price{
    color:#E65E0D;
    margin-right:10px;
  }
  .footer_right_pay{
    background:#555555;
    text-align:center;
    color:#fff;
    height: 45px;
    line-height:45px;
    width:100px;
  }
  .hasItem{
      background:red !important;
  }

  .slide{
        width: 100%;
        position: relative;
        height: 120px;
		border-bottom: 1px solid #eeeeee;
    }
    .contents_wrapper[data-type="0"]{
        right:0
    }
    .contents_wrapper[data-type="1"]{
        right:80px;
    }
    .contents_wrapper{
        width: 100%;
        height: 100%;
        position: absolute;
        transition: right 0.3s ease-in-out;
        z-index: 99;
      background: #ffffff;
        /*background: #222222;*/
        /*color: #ffffff;*/
    }
    .contents{
        width: 100%;
    }
    .delete{
        color:#fff;
        height: 100%;
        text-align: center;
        width:80px;
        background: red;
        line-height: 120px;
        position: absolute;
        right:0;
    }
    .cart_list_item{
      width:100%;
      height: 100%;
      display:flex;
      flex-wrap:nowrap;
      /*margin:0 0 0 10px;*/
      align-items:center;
      border-bottom: 1px solid #eee;
  }
  .cart_list_item_pic{
    width:70px;
    height: 70px;
    /*margin-left:10px;*/
  }
  .cart_list_item_right{
    margin-left:10px;
    width:59%;
    /* height: 100%; */
	height: 80px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
  }
  .cart_list_item_name{
	font-size: 15px;
	color: #252426;
    width:100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 10px;
  }
  .cart_list_item_desc{
    margin-bottom:10px;
    width:100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }



  .count{
        width:100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        /*color: #ffffff;*/
    }
    .count_btn{
        margin-right:10px;
        display: flex;
        width:100px;
        height: 25px;
        line-height: 25px;
        text-align: center;
    }
    .decrease,.increase{
        border: 1px solid #eee;
        width:30px;
        height: 100%;
    }
    .decrease{
        border-radius: 5px 0 0 5px;
    }
    .increase{
        border-radius: 0 5px 5px 0;
    }
    .input_num{
      position: relative;
      flex:1;
    }
    .input_num_layer{
      position: absolute;
      width:100%;
      height:100%;
      z-index:3;
    }
    .count_btn input{

        width:100%;
        border-top:1px solid #eee;
        border-bottom:1px solid #eee;
        height:100%;
        min-height: 0 !important;
    }
    .decrease_least{
      background: #eeeeee;
        /*background:#999999;*/
    }

    .cart_empty{
	  font-size: 28rpx;
	  color: #B5B5B5;
      width:100%;
      position:absolute;
      top:80px;
      margin:0 auto;
      display:flex;
      flex-wrap:wrap;
      justify-content:center;
      align-items:center
    }
    .cart_empty img{
      width:40px;
      height: 40px;
    }
    .cart_empty view{
      width:100%;
      text-align:center;
      font-size:18px;
      margin-top:10px;
    }
</style>
